//
//  DoctorReserveViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/26.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON

struct DoctorReserveModel: HandyJSON {
    var id: String?
    var deptId: String?
    var docName: String?
    var deptName: String?
    var hospitalName: String?
    var jobTitleName: String?
    var fee: String?
    var docGoodAtNames: String?
    var docGoodAt: String?
    var bucket: String?
    var num: Int = 0
    var url: String?
    var thumbnailUrl: String?
    var score: Float = 0.0
    var isPrescription: Int = 0
    var diagType: Int = 0
    var isRecommend: Int = 0
}

struct DoctorReserveViewModel {
    var models: [DoctorReserveModel]
    
    var numberOfRows: Int { return models.count }
    
    func viewModel(of indexPath: IndexPath) -> DoctorReserveRowViewModel {
        return DoctorReserveRowViewModel(model: models[indexPath.row])
    }
    
    mutating func loadMore(with models: [DoctorReserveModel]) {
        self.models += models
    }
}

struct DoctorReserveRowViewModel {
    let model: DoctorReserveModel
    
    var num : String {return String(format: "%d", model.num)}
    var doctorId: String { return model.id ?? "" }
    var departmentId: String { return model.deptId ?? "" }
    var doctorName: String { return model.docName ?? "" }
    var hospitalName: String { return model.hospitalName ?? "" }
    var department: String { return model.deptName ?? "" }
    var office: String { return model.jobTitleName ?? "" }
    var specialty: String { return "擅长：\(model.docGoodAtNames ?? "")"}
    var thumbnailUrl: String { return model.thumbnailUrl ?? "" }
    var score: String { return "\(model.score)" }
    var isPrescription: Int { return model.isPrescription }
    var fee: String { return model.fee ?? "" }
    var prescriptionStr: String {
        return isPrescription == 1 ? "处方" : "非处方"
    }
    var prescriptionColor: UIColor? {
        return isPrescription == 1 ? .orangeColor : .textLight
    }
    var doctorType: DoctorType { return DoctorType(rawValue: model.diagType) ?? .all }
    
    var isRecommend: Bool { return model.isRecommend == 1 ? true : false }
    
    func cellHeight(type: DoctorType = .all) -> CGFloat {
        let h = specialty.height(font: .regular(14), width: screenW - 128)
        if type == .all {
            return doctorType == .none ? (140 + h) : (140 + 50 + h)
        } else {
            return 140 + h
        }
    }
}

extension DoctorReserveViewModel {
    /// diagType 1-图文咨询 3-云门诊
    static func getDoctorReserveList(type : Int,
                                     departmentId: String = "",
                                     diagType: Int = 0,
                                     content: String = "",
                                     scheduleTime: String = "",
                                     timeInterval: String = "",
                                     current: Int = 1,
                                     size: Int = 10,
                                     code: String = "",
                                     isPrescription: String = "",
                                     isRecommend: Int = 0,
                                     success: @escaping (_ models: [DoctorReserveModel]) -> Void,
                                     failure: @escaping (_ errorMsg: String?) -> Void) {
        var paras: [String: Any] = [
            "deptId": departmentId,
            "diagType": diagType,
            "content": content,
            "scheduleTime": scheduleTime,
            "timeInterval": timeInterval,
            "current": current,
            "size": size,
            "code": code,
            "isPrescription": isPrescription,
            "isRecommend": isRecommend,
        ]
        
        var target = ApiManager.doctorReserveList_doctor(paras: paras)

        if type == 1{
            if code.isEmpty{
                paras["code"] = "0"
            }
            if departmentId.isEmpty{
                paras["deptId"] = "0"
            }
            target = ApiManager.doctorReserveList_doctor(paras: paras)
        }else {
            target = ApiManager.doctorReserveList_query(paras: paras)
        }
       
        
        HttpTool.shared.request(target: target, success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let models = JSONDeserializer<DoctorReserveModel>.deserializeModelArrayFrom(json: json["data"]["records"].description) as? [DoctorReserveModel] {
                    success(models)
                } else {
                    failure("请求数据发生错误，稍后重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    /// 生成云门诊订单
    static func generateCloudOrder(userId: Int,
                                   scheduleId: String,
                                   patientId: String,
                                   condition: String,
                                   imgIdsStr: String,
                                   allergyHistory: String,
                                   pastHistory: String,
                                   success: @escaping (_ model: PayOrderModel) -> Void,
                                   failure: @escaping (_ errorMsg: String?) -> Void)
    {
        let paras: [String: Any] = [
            "userId": userId,
            "scheduleId": scheduleId,
            "patientId": patientId,
            "oneselfState": condition,
            "resourceId": imgIdsStr,
            "allergyHistory": allergyHistory,
            "pastHistory": pastHistory
        ]
        HttpTool.shared.request(target: ApiManager.generateCloudOrder(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let model = JSONDeserializer<PayOrderModel>.deserializeFrom(json: json["data"].description) {
                    success(model)
                } else {
                    failure("请求数据发生错误，稍后重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    /// 获取云门诊号源价格
    static func getCloudNumberAmount(doctorId: String, scheduleId: String, bizType: Int = 2, finished: @escaping (_ amount: String, _ errorMsg: String?) -> Void) {
        let paras: [String: Any] = [
            "doctorId": doctorId,
            "scheduleId": scheduleId,
            "bizType": bizType
        ]
        HttpTool.shared.request(target: ApiManager.getCloudNumberAmount(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                finished("", json["message"].description)
            case .success:
                finished(json["data"]["price"].description, nil)
            }
        }) { errorMsg in
            finished("", errorMsg)
        }
    }
}
